package com.white.crackwifi.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangzy
 * @Description: IO工具类
 * @date 2019/12/24 15:46
 */
public class IOUtil {

    private IOUtil(){}

    /**
     * 将文件内容读出字符串
     * @param file
     * @return
     */
    public static String fileToString(File file){
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
            String s; // 依次循环，至到读的值为空
            StringBuilder sb = new StringBuilder();
            while ((s = reader.readLine()) != null) {
                sb.append(s);
            }
            reader.close();
            return sb.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将文件数据读到银盘
     * @param data 数据
     * @param path 路径
     */
    public static void stringToFile(String data, String path , String fileName) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String p = path.endsWith("/") ? path.concat(fileName) : path.concat("/".concat(fileName));
        FileWriter fileWriter = new FileWriter(p);
        fileWriter.write(data);
        fileWriter.close();
    }

    /**
     * 将文件数据读到银盘
     * @param data 数据
     * @param path 路径
     */
    public static void stringToFileAppend(String data, String path,String fileName) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String p = path.endsWith("/") ? path.concat(fileName) : path.concat("/".concat(fileName));
        FileWriter fileWriter = new FileWriter(p);
        fileWriter.write(data);
        fileWriter.close();
    }



    /**
     * 文件读取行数据,存入LIST
     * @param file
     * @return
     */
    public static List<String> fileToListString(File file){
        List<String> stringList = new ArrayList<>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                stringList.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringList;
    }

}
